package wbsocketload

import (
	"Go-by-Example/lib"
	"log"
	"net/http"
	"strconv"
	"time"
)

var (
	websocketAddress = "/sockets/stb" //websocket地址

	fn = func(message []byte, hub *lib.Hub) error { //反调函数
		log.Println("I access message:", string(message))
		// hub.Broadcast <- message
		return nil
	}
	hub = lib.NewHub(fn) //新建一个用户
)

//wenSocketInit wesocket启动
func wenSocketInit() {

	go hub.Run() //开始获取用户中传送的数据

	http.HandleFunc(websocketAddress, func(res http.ResponseWriter, r *http.Request) {
		lib.ServeWs(hub, res, r)
	})
}

//websocketLoad socket监听,入口函数
func websocketLoad() {
	wenSocketInit()
	log.Println("start listen 8080")
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		log.Panic(err)
	}
}

//websocketTest 测试函数
func websocketTest() {
	time.Sleep(time.Second * 10)
	log.Println("start send num")
	ticker := time.NewTicker(time.Second)
	num := 0
	for {
		if num == 10 {
			ticker.Stop()
			break
		}
		log.Println("send now:", num)
		<-ticker.C
		hub.Broadcast <- []byte("this is time:" + strconv.Itoa(num))
		num++
	}
	log.Println("stop send num")
}
